package com.example.descrambler;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

@SuppressWarnings("serial")
public class DescramblerServlet extends HttpServlet {
	
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	  resp.setContentType("text/html");
	  VelocityContext context = new VelocityContext();
	  VelocityEngine ve = VelocityHelper.getVelocityEngine();
    Template template = ve.getTemplate("/com/example/descrambler/index.vm");
    template.merge(context, resp.getWriter());
  }
  
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    resp.setContentType("text/html");
    String word = req.getParameter("word");
    VelocityContext context = new VelocityContext();
    context.put("scramble", word);
    String result = descramble(resp, word);
    context.put("found", result);
    
    VelocityEngine ve = VelocityHelper.getVelocityEngine();
    Template template = ve.getTemplate("/com/example/descrambler/index.vm");
    template.merge(context, resp.getWriter());
  }

private String descramble(HttpServletResponse resp, String word) throws IOException {
	ServletContext servletContext = getServletContext();
    InputStream is = servletContext.getResourceAsStream("/WEB-INF/10kwords.txt");
    if (is == null)
    	resp.getWriter().println("uh-oh, stream was null");
    InputStreamReader isr = new InputStreamReader(is);
    WordIndex index = new WordIndex(isr);
    String result = index.lookup(word);
	return result;
}

  private void printForm(HttpServletResponse resp) throws IOException {
    resp.getWriter().println("<form action=\"/descrambler\" method=\"post\">");
    resp.getWriter().println("<input type=\"text\" id='word' name=\"word\" />");
    resp.getWriter().println("<input type=\"submit\" value=\"Descramble\" />");
    resp.getWriter().println("</form>");
  }
}
